package org.hscoder.springboot.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class SecurityController {

    @GetMapping("/")
    @ResponseBody
    public String index() {
        return "Home";
    }

    @RequestMapping("/user")
    @ResponseBody
    public String user() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = null;
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else {
            username = principal.toString();
        }
        return "Welcome back," + username;
    }

    @GetMapping("/admin")
    @ResponseBody
    public String admin() {
        return "Admin Page";
    }

    @GetMapping("/login")
    public String login(
            HttpSession session,
            ModelMap model
    ) {
        //获取登录失败异常
        AuthenticationException authenticationException = (AuthenticationException)
                session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        if (authenticationException != null) {
            model.addAttribute("error", authenticationException.getMessage());
        }
        return "login";
    }

}
